// ignore_for_file: use_build_context_synchronously, file_names

import 'dart:io';
import 'dart:math';

import 'package:fbroadcast/fbroadcast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_page/video/video_full_page.dart';
import 'package:xvideos/hj_page/video/video_logic.dart';
import 'package:xvideos/hj_page/video/view/detail_top_right_view.dart';
import 'package:xvideos/hj_page/video/view/newer_timer_ac_view.dart';
import 'package:xvideos/hj_page/video/view/video_ad_widget.dart';
import 'package:xvideos/hj_page/video/view/video_buffer_loading_widget.dart';
import 'package:xvideos/hj_page/video/view/video_mask_buy_view.dart';
import 'package:xvideos/hj_page/video/view/video_menu_view.dart';
import 'package:xvideos/hj_page/video/view/video_tabbar_menu_widget.dart';
import 'package:xvideos/hj_page/video/view/video_tabbar_view.dart';
import 'package:xvideos/hj_utils/api_service/acg_service.dart';
import 'package:xvideos/hj_utils/api_service/vid_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/screen.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/event_bus/event_bus_util.dart';
import 'package:xvideos/tools_base/event_bus/events.dart';

import '../../alert_business/video/comic_buy_alert.dart';
import '../../alert_business/video/video_buy_alert.dart';
import '../../alert_business/video/vip_dailog.dart';
import '../../config/config.dart';
import '../../hj_model/acg/comic_chapters_model.dart';
import '../../hj_model/cartoon_media_info.dart';
import '../../hj_model/media_content.dart';
import '../../hj_model/splash/ads_model.dart';
import '../../hj_model/video_model.dart';
import '../../hj_utils/event_tracking_manager.dart';
import '../../hj_utils/free_play_count_manager.dart';
import '../../hj_utils/history_record_util.dart';
import '../../hj_utils/player_util.dart';
import '../../hj_utils/sliver_delegate.dart';
import '../../tools_base/debug_log.dart';
import '../../tools_base/global_store/local_ads_info_store.dart';
import '../../tools_base/global_store/store.dart';
import '../../tools_base/video_download/video_download_manager.dart';
import '../../tools_base/widget/net_image_widget.dart';
import '../home_business/widget/home_limit_activity_widget.dart';
import 'cartoon/model_exchange.dart';

class VideoPage extends StatefulWidget {
  final bool isCartoon;
  final VideoModel? model;
  final String? id;
  final String? videoCover;

  VideoPage({
    super.key,
    this.model,
    this.isCartoon = false,
    this.id,
    this.videoCover,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoPageState();
  }
}

class _VideoPageState extends State<VideoPage> {
  late String logicTag = "${DateTime.now().millisecondsSinceEpoch}";
  late VideoLogic logic = VideoLogic(vid: widget.id ?? widget.model?.id, isCartoon: widget.isCartoon);

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: logic,
      tag: logicTag,
      builder: (_) {
        return Scaffold(
          body: SafeArea(
            child: Stack(
              fit: StackFit.expand,
              children: [
                NestedScrollView(
                  key: ValueKey("${logic.videoModel?.id}${logic.scrollController.initialScrollOffset}"),
                  controller: logic.scrollController,
                  headerSliverBuilder: (context, innerBoxIsScrolled) {
                    return [
                      if (logic.initedVideoController)
                        SliverPersistentHeader(
                          pinned: true,
                          key: ValueKey("Ratio_${logic.videoModel?.id}"),
                          delegate: MySliverDelegate(
                            maxHeight: max(Get.width / logic.normalRatio, Get.width / logic.videoRatio),
                            minHeight: Get.width / logic.normalRatio,
                            child: _buildPlayContent(),
                          ),
                        )
                      else
                        SliverPersistentHeader(
                          pinned: true,
                          delegate: MySliverDelegate(
                            maxHeight: Get.width / logic.normalRatio,
                            minHeight: Get.width / logic.normalRatio,
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                NetworkImageLoader(
                                    imageUrl: logic.videoModel?.cover ?? widget.videoCover ?? "", borderRadius: 0),
                                Center(child: CupertinoActivityIndicator(color: AppColors.actionRed, radius: 15)),
                              ],
                            ),
                          ),
                        ),
                      if (logic.videoModel != null) ...[
                        SliverToBoxAdapter(
                          child: NewerTimerAcView(
                            videoPlayerController: logic.videoPlayerController,
                            videoModel: logic.videoModel,
                          ),
                        ),
                        SliverPersistentHeader(
                          pinned: true,
                          key: ValueKey("menu_${logic.videoModel?.id}"),
                          delegate: MySliverDelegate(
                            maxHeight: 42,
                            minHeight: 42,
                            child: Container(
                              color: AppColors.primaryColor,
                              child: VideoTabbarMenuWidget(
                                logic.pageController,
                                model: logic.videoModel,
                              ),
                            ),
                          ),
                        )
                      ]
                    ];
                  },
                  body: SizedBox(
                    height: screen.screenHeight,
                    child: _buildTabDetailInfo(),
                  ),
                ),
                Positioned(
                  right: 12,
                  bottom: 112,
                  child: HomeLimitActivityWidget(),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildTabDetailInfo() {
    return Listener(
      onPointerDown: (_) {
        eventBus.emit(LongVideoMenuEvent());
      },
      child: VideoTabBarView(
        model: logic.videoModel,
        controller: logic.videoPlayerController,
        currentEpisode: logic.currentEpisode,
        pageController: logic.pageController,
        callback: () {
          logic.setNoAdVideo();
        },
        vmCallback: (model) {
          if (widget.isCartoon) {
            logic.exchangeCartoonPlayer(model);
          } else {
            logic.startVideoPlayer(model: model);
          }
        },
        episoCallback: (index) {
          logic.exchangeEpisod(index);
        },
      ),
    );
  }

  Widget _buildPlayContent() {
    return Container(
      color: AppColors.primaryColor,
      child: Stack(
        fit: StackFit.expand,
        children: [
          GestureDetector(
            onTap: () {
              if (logic.videoPlayerController?.value.isPlaying == true) {
                logic.videoPlayerController?.pause();
              } else {
                logic.videoPlayerController?.play();
              }
            },
            child: Container(
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: logic.videoRatio,
                child: logic.videoPlayerController != null ? VideoPlayer(logic.videoPlayerController!) : SizedBox(),
              ),
            ),
          ),
          if (logic.videoPlayerController?.value.isInitialized != true)
            NetworkImageLoader(imageUrl: logic.videoModel?.cover ?? widget.videoCover ?? "", borderRadius: 0),
          if (logic.videoPlayerController?.value.isInitialized == true) ...[
            Positioned(
              bottom: 54,
              right: 0,
              child: DetailTopRightView(
                key: ValueKey("status_top_${logic.videoModel?.id}"),
                controller: logic.videoPlayerController!,
                videoModel: logic.videoModel,
              ),
            ),
            VideoMenuView(
              key: ValueKey("VideoMenuView_${logic.videoModel?.id}"),
              controller: logic.videoPlayerController!,
              videoModel: logic.videoModel,
              onBuyEvent: () {
                logic.showBuyMask();
              },
              callback: () async {
                logic.toFullPage();
              },
            ),
          ],
          Positioned.fill(
            child: VideoBufferLoadingWidget(logic.videoPlayerController),
          ),
          Positioned.fill(
            child: Obx(
              () => Visibility(
                visible: logic.isShowBuyView.value,
                child: VideoMaskBuyView(
                  logic.videoModel,
                  videoPlayerController: logic.videoPlayerController,
                  currentEpisode: logic.currentEpisode,
                ),
              ),
            ),
          ),
          if (logic.isShowVideoAd && logic.videoAdsList.isNotEmpty)
            Container(
              padding: const EdgeInsets.fromLTRB(60, 60, 60, 34),
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: 720 / 350,
                child: VideoAdWidget(
                  adsInfos: logic.videoAdsList,
                  videoModel: logic.videoModel,
                  showBackArrow: false,
                  finisiCallback: () {
                    logic.setNoAdVideo();
                    logic.safeFlashUI();
                  },
                  toVipCallback: () async {
                    logic.clickAdToVip();
                  },
                ),
              ),
            ),
          // if (widget.isCartoon == true)
          Align(
            alignment: Alignment.topLeft,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Container(
                color: Colors.transparent,
                width: 30,
                height: 30,
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(top: 10, left: 18.w),
                child: Image.asset(
                  "back_circle.png".commonImgPath,
                  width: 24,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
